package com.orharlan.carassistant.features;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.orharlan.carassistant.datamodel.Datamodel;

import android.os.AsyncTask;

public class GetWoeid
{
	// Example for "New York"
	// http://query.yahooapis.com/v1/public/yql?q=select*from geo.places where
	// text="New York"&format=xml
	final String yahooPlaceApisBase = "http://query.yahooapis.com/v1/public/yql?q=select*from%20geo.places%20where%20text=";
	final String yahooapisFormat = "&format=xml";
	String yahooPlaceAPIsQuery;
	Datamodel data;

	public GetWoeid( )
	{
		data = Datamodel.singleton( );
	}

	public void startQuery( )
	{

		new MyQueryYahooPlaceTask( ).execute( );

	}

	private class MyQueryYahooPlaceTask extends AsyncTask< Void, Void, Void >
	{

		ArrayList< String > possibleWoeid;

		@Override
		protected Void doInBackground( Void... arg0 )
		{
			possibleWoeid = QueryYahooPlaceAPIs( );

			// Save the WOEID in the datamodel
			if( possibleWoeid.size( ) > 0 )
			{
				data.setWoeid( possibleWoeid.get( 0 ) );
			}
			return null;
		}

		@Override
		protected void onPostExecute( Void result )
		{
			// Update GUI, if you want
			super.onPostExecute( result );
		}

	}

	private ArrayList< String > QueryYahooPlaceAPIs( )
	{
		yahooPlaceAPIsQuery = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D%22" + data.getCurrentLatitude( ) + "%2C" + data.getCurrentLongitude( ) + "%22%20and%20gflags%3D%22R%22&diagnostics=true";
		String woeidString = QueryYahooWeather( yahooPlaceAPIsQuery );
		Document woeidDoc = convertStringToDocument( woeidString );
		return parseWOEID( woeidDoc );
	}

	private ArrayList< String > parseWOEID( Document srcDoc )
	{
		ArrayList< String > listWOEID = new ArrayList< String >( );

		NodeList nodeListDescription = srcDoc.getElementsByTagName( "woeid" );
		if( nodeListDescription.getLength( ) >= 0 )
		{
			for( int i = 0; i < nodeListDescription.getLength( ); i++ )
			{
				listWOEID.add( nodeListDescription.item( i ).getTextContent( ) );
			}
		}
		else
		{
			listWOEID.clear( );
		}

		return listWOEID;
	}

	private Document convertStringToDocument( String src )
	{
		Document dest = null;

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance( );
		DocumentBuilder parser;

		try
		{
			parser = dbFactory.newDocumentBuilder( );
			dest = parser.parse( new ByteArrayInputStream( src.getBytes( ) ) );
		}
		catch( ParserConfigurationException e1 )
		{
			e1.printStackTrace( );
		}
		catch( SAXException e )
		{
			e.printStackTrace( );
		}
		catch( IOException e )
		{
			e.printStackTrace( );
		}

		return dest;
	}

	private String QueryYahooWeather( String queryString )
	{
		String qResult = "";

		HttpClient httpClient = new DefaultHttpClient( );
		HttpGet httpGet = new HttpGet( queryString );

		try
		{
			HttpEntity httpEntity = httpClient.execute( httpGet ).getEntity( );

			if( httpEntity != null )
			{
				InputStream inputStream = httpEntity.getContent( );
				Reader in = new InputStreamReader( inputStream );
				BufferedReader bufferedreader = new BufferedReader( in );
				StringBuilder stringBuilder = new StringBuilder( );

				String stringReadLine = null;

				while( ( stringReadLine = bufferedreader.readLine( ) ) != null )
				{
					stringBuilder.append( stringReadLine + "\n" );
				}

				qResult = stringBuilder.toString( );
			}
		}
		catch( ClientProtocolException e )
		{
			e.printStackTrace( );
			;
		}
		catch( IOException e )
		{
			e.printStackTrace( );
		}

		return qResult;
	}

}
